#####
# Replication for: "Can Political Speech Foster Tolerance of Immigrants?" by Schleiter, Tavits, and Ward.
# Figure S.4
#####

library(here)
library(data.table)
library(ggplot2)
library(ggstance)

# source the custom functions
source("functions.R")

# load the pooled data if not already in workspace
if(!exists("pooled")){
  pooled <- fread(here("data", "pooled.csv"))
}


# Plot preparation --------------------------------------------------------

to_plot <- pooled[replication == 0, .(Treatment, sapply(.SD, center)), .SDcols = c("mechanism_CH", "mechanism_CS", "mechanism_NM")][ , lapply(.SD, mean, na.rm = T), by = Treatment, .SDcols = c("mechanism_CH", "mechanism_CS", "mechanism_NM")]

to_plot <- melt(to_plot[Treatment != "Sleep"], id.vars = c("Treatment"))

facet_labs <- c(
  "Tolerance and acceptance of diversity are American values.",
  "Our economy benefits from the work of immigrants.",
  "All people, no matter where they are born, share a common humanity."
)

to_plot[ , facet_lab := factor(
  fcase(
    variable == "mechanism_NM", facet_labs[1],
    variable == "mechanism_CS", facet_labs[2],
    variable == "mechanism_CH", facet_labs[3]),
  levels = facet_labs
  )]

to_plot[ , Treatment := factor(
  fifelse(Treatment == "Information", "Countering Stereotypes", Treatment),
  levels = c("Common Humanity", "Countering Stereotypes", "Norms")
)]


# Plot and save -----------------------------------------------------------

fig_s4 <- ggplot(to_plot, aes(x = value, y = 1, fill = Treatment)) +
  geom_barh(position = position_dodgev(), stat = "identity") +
  scale_fill_grey(name = "Treatment:", guide = guide_legend(reverse = TRUE)) +
  facet_wrap( ~ facet_lab , ncol = 1) +
  scale_y_continuous(breaks = NULL) +
  ylab(NULL) +
  xlab("Agreement with Statement (Mean = 0, SD = 1)") +
  theme(
    legend.position = "bottom",
    strip.text.x = element_text(size = 12, hjust = 0.5),
    strip.background = element_rect(fill= "white")
    ) 

ggsave(here("SI", "figure_s4.pdf"), fig_s4, width = 6, height = 8)
